//
//  CTabBar.m
//  OperationPro
//
//  Created by yaxue wang on 16/9/27.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "CTabBar.h"
#import "CTabBarItem.h"

@interface CTabBar()
@property (nonatomic, strong) NSMutableArray *tabBarViews;
@end

@implementation CTabBar

- (void) addTabBar:(UITabBarItem *) tabbaritem{
    [self.tabBarViews addObject:[CTabBarItem initWithTabBarItem:tabbaritem]];
    [self reloadView];
}

- (void) addTabBarItem:(CTabBarItem *)tabbaritem{
    [self.tabBarViews addObject:tabbaritem];
    [self reloadView];
}

- (void)clear{
    [self.tabBarViews removeAllObjects];
}

- (void) reloadView{
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
    float width = WindowWidth / self.tabBarViews.count;
    int i = 0;
    NSMutableArray *tabbaritems = [NSMutableArray array];
    for (CTabBarItem *tabbar in self.tabBarViews) {
        [tabbaritems addObject:tabbar];
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(width * i, 0, width, self.frame.size.height)];
        [self addSubview:view];
        
        [view addSubview:tabbar];
        [tabbar setCenter:CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2)];
        
        [view bk_whenTapped:^{
            if (self.Delegate) {
                [self.Delegate CTabBar:self selectedIndex:i];
                [self.Delegate CTabBar:self selectedTabBarItem:tabbar];
            }
            [self setSelectIndex:i];
        }];
        i ++;
    }
    _tabBarItems = tabbaritems;
    [self setSelectIndex:0];
    self.backgroundColor=[UIColor whiteColor];
    UIView *topLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WindowWidth, .5)];
    [self addSubview:topLineView];
    [topLineView setBackgroundColor:C(@"ebebeb")];
}

- (void)setSelectIndex:(NSInteger)selectIndex{
    _selectIndex = selectIndex;
    for (int i = 0; i < self.tabBarViews.count; i ++) {
        CTabBarItem *baritem = self.tabBarViews[i];
        [baritem setSelected:selectIndex == i];
    }
}

- (void)setShowIndex:(NSInteger)showIndex{
    //    if (self.tabBarViews.count > showIndex + 1) {
    //        return;
    //    }
    if (self.Delegate) {
        [self.Delegate CTabBar:self selectedIndex:showIndex];
        [self.Delegate CTabBar:self selectedTabBarItem:self.tabBarViews[showIndex]];
    }
    [self setSelectIndex:showIndex];
}

- (CTabBarItem *) tabBarItem:(NSInteger) index{
    return self.tabBarItems[index];
}

- (NSMutableArray *)tabBarViews{
    if (_tabBarViews == nil) {
        _tabBarViews = [NSMutableArray array];
    }
    return _tabBarViews;
}
@end
